import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/product_controller.dart';
import '../../../translations/app_translations.dart';

class ProductView extends GetView<ProductController> {
  const ProductView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(LocaleKeys.product.tr),
        centerTitle: true,
        actions: [
          IconButton(
            onPressed: () {
              showSearch(
                context: context,
                delegate: ProductSearchDelegate(controller),
              );
            },
            icon: const Icon(Icons.search),
          ),
        ],
      ),
      body: RefreshIndicator(
        onRefresh: () => controller.refreshProducts(),
        child: Obx(() {
          if (controller.isLoading.value) {
            return const SizedBox(
              height: 80,
              child: Center(
                child: CircularProgressIndicator(),
              ),
            );
          }
          
          if (controller.products.isEmpty) {
            return SizedBox(
              height: 200,
              child: Center(
                child: Text(LocaleKeys.noDevices.tr),
              ),
            );
          }
          
          return Stack(
            children: [
              ListView.builder(
                controller: controller.scrollController,
                itemCount: controller.products.length + 1, // 额外添加一个用于显示加载更多
                itemBuilder: (context, index) {
                  if (index == controller.products.length) {
                    if (controller.isLoadingMore.value) {
                      return const SizedBox(
                        height: 60,
                        child: Center(
                          child: CircularProgressIndicator(),
                        ),
                      );
                    }
                    return const SizedBox.shrink();
                  }
                  
                  final product = controller.products[index];
                  return Card(
                    margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    child: ListTile(
                      leading: _buildProductTypeIcon(product.nodeType),
                      title: Text(product.productName ?? LocaleKeys.unknownProduct.tr),
                      subtitle: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('${LocaleKeys.productKey.tr}: ${product.productKey}'),
                          Text('${LocaleKeys.nodeType.tr}: ${_getNodeTypeText(product.nodeType)}'),
                        ],
                      ),
                      trailing: _buildStatusChip(product.status),
                      onTap: () {
                        final int productId = product.productId;
                        controller.viewProductDetail(productId);
                                            },
                    ),
                  );
                },
              ),
              
              // 顶部加载指示器
              Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: Obx(() => controller.isRefreshing.value
                  ? const SizedBox(
                      height: 2,
                      child: LinearProgressIndicator(),
                    )
                  : const SizedBox.shrink()
                ),
              ),
            ],
          );
        }),
      ),
      floatingActionButton: FloatingActionButton(
        tooltip: LocaleKeys.addDevice.tr,
        onPressed: () => controller.addNewProduct(),
        child: const Icon(Icons.add),
      ),
    );
  }
  
  Widget _buildProductTypeIcon(int? nodeType) {
    IconData iconData;
    Color iconColor;
    
    switch (nodeType) {
      case 1: // 直连设备
        iconData = Icons.devices;
        iconColor = Colors.blue;
        break;
      case 2: // 网关设备
        iconData = Icons.router;
        iconColor = Colors.green;
        break;
      case 3: // 子设备
        iconData = Icons.device_hub;
        iconColor = Colors.orange;
        break;
      default:
        iconData = Icons.device_unknown;
        iconColor = Colors.grey;
    }
    
    final Color bgColor = Color.fromRGBO(
      iconColor.red, 
      iconColor.green, 
      iconColor.blue, 
      0.16
    );
    
    return CircleAvatar(
      backgroundColor: bgColor,
      child: Icon(iconData, color: iconColor),
    );
  }
  
  Widget _buildStatusChip(int? status) {
    String label;
    Color color;
    
    switch (status) {
      case 0: // 开发中
        label = LocaleKeys.statusInfo.tr;
        color = Colors.orange;
        break;
      case 1: // 已发布
        label = LocaleKeys.statusSuccess.tr;
        color = Colors.green;
        break;
      default:
        label = LocaleKeys.unknown.tr;
        color = Colors.grey;
    }
    
    return Chip(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 0),
      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
      backgroundColor: color,
      label: Text(label, style: const TextStyle(color: Colors.white, fontSize: 12)),
    );
  }
  
  String _getNodeTypeText(int? nodeType) {
    switch (nodeType) {
      case 1:
        return LocaleKeys.productTypeDevice.tr;
      case 2:
        return LocaleKeys.productTypeGateway.tr;
      case 3:
        return LocaleKeys.productTypePlatform.tr;
      default:
        return LocaleKeys.statusUnknown.tr;
    }
  }
}

class ProductSearchDelegate extends SearchDelegate<String> {
  final ProductController controller;
  
  ProductSearchDelegate(this.controller);
  
  IconData _buildProductTypeIcon(int? nodeType) {
    switch (nodeType) {
      case 1: return Icons.devices;
      case 2: return Icons.router;
      case 3: return Icons.device_hub;
      default: return Icons.device_unknown;
    }
  }
  
  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        onPressed: () {
          query = '';
        },
        icon: const Icon(Icons.clear),
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      onPressed: () {
        close(context, '');
      },
      icon: const Icon(Icons.arrow_back),
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    controller.searchProducts(query);
    return _buildSearchResults();
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    if (query.isEmpty) {
      return Center(
        child: Text(LocaleKeys.searchDeviceHint.tr),
      );
    }
    
    controller.searchProducts(query);
    return _buildSearchResults();
  }
  
  Widget _buildSearchResults() {
    return Obx(() {
      if (controller.isSearching.value) {
        return const Center(child: CircularProgressIndicator());
      }
      
      if (controller.searchResults.isEmpty) {
        return Center(
          child: Text(LocaleKeys.noMatchingDevices.tr),
        );
      }
      
      return ListView.builder(
        itemCount: controller.searchResults.length,
        itemBuilder: (context, index) {
          final product = controller.searchResults[index];
          final int productId = product.productId;
          return ListTile(
            title: Text(product.productName ?? LocaleKeys.unknownProduct.tr),
            subtitle: Text(product.productKey ?? ''),
            leading: Icon(
              _buildProductTypeIcon(product.nodeType),
            ),
            onTap: () {
              controller.viewProductDetail(productId);
              close(context, '');
                        },
          );
        },
      );
    });
  }
} 